package com.greatchn.security_demo.filter;

import cn.hutool.core.util.StrUtil;
import com.greatchn.security_demo.bean.CustomUserDetailsService;
import com.greatchn.security_demo.util.ApiAssert;
import com.greatchn.security_demo.web.srv.LoginSrv;
import com.greatchn.security_demo.web.po.Token;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @TokenFilter: token filter
 * @author: ZBoHang
 * @time: 2023/2/8 13:25
 */
@Component
public class TokenFilter extends GenericFilterBean {

    @Resource
    private LoginSrv loginSrv;
    @Resource
    private CustomUserDetailsService customUserDetailsService;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws ServletException, IOException {
        // TODO: 2023/2/8
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;

        String authToken = httpServletRequest.getHeader("auth");
        if (StrUtil.isNotBlank(authToken)) {
            // 解析用户
            Token token = this.loginSrv.getTokenByTokenKey(authToken);
            ApiAssert.notNull(token, "令牌不存在!");
            // 查询用户信息
            UserDetails details = this.customUserDetailsService.loadUserByUsername(token.getUserName());
            if (this.loginSrv.checkToken(authToken)) {

                UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =
                        new UsernamePasswordAuthenticationToken(details, details.getPassword(), details.getAuthorities());
                // 存放认证信息 恢复session - 若没有则会提示登录
                SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
            }
        }
        // 调用后续的Filter,未能复原“session”，SecurityContext中没有想过信息，后面的流程会检测出"需要登录"
        filterChain.doFilter(servletRequest, servletResponse);
    }
}
